package com.zxy.fmmall.service.job;

import com.github.wxpay.sdk.WXPay;
import com.zxy.fmmall.dao.OrderItemMapper;
import com.zxy.fmmall.dao.OrdersMapper;
import com.zxy.fmmall.dao.ProductSkuMapper;
import com.zxy.fmmall.entity.OrderItem;
import com.zxy.fmmall.entity.Orders;
import com.zxy.fmmall.entity.ProductSku;
import com.zxy.fmmall.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class OrderTimeOutCheckJob {
    WXPay wxpay = new WXPay(new MyPayConfig());
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrdersService ordersService;
    @Scheduled(cron = "0/60 * * * * ?")
    public void checkAndCloseOrder(){
        try {
            // 1.查询超过30min订单状态依旧为 未支付状态的订单
            System.out.println(" ================= " );
            Example example = new Example(Orders.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("status","1");
            Date time = new Date(System.currentTimeMillis() - 30*60*1000);
            criteria.andLessThan("createTime",time);
            List<Orders> orders = ordersMapper.selectByExample(example);
            System.out.println("orders = " + orders.size());
            // 2.访问微信平台接口，确认当前订单最终的支付状态
            for (int i = 0; i < orders.size(); i++) {
                Orders order = orders.get(i);
                HashMap<String, String> map = new HashMap<>();
                map.put("out_trade_no",order.getOrderId());
                Map<String, String> resp = wxpay.orderQuery(map);
                System.out.println("resp = " + resp);
                if("SUCCESS".equalsIgnoreCase(resp.get("trade_state"))){
                    // 2.1如果订单已经支付，则修改订单状态为/代发货/已支付
                    Orders orders1 = new Orders();
                    orders1.setStatus("2");
                    orders1.setOrderId(order.getOrderId());
                    ordersMapper.updateByPrimaryKeySelective(orders1);
                }else if("NOTPAY".equalsIgnoreCase(resp.get("trade_state"))){
                    // 2.2 如果确实未支付，则取消订单
                    wxpay.closeOrder(map);
                    // a.像微信支付平台发送请求，关闭当前订单的支付连接
                    // b.修改当前订单：status = 6；已关闭 close_type = 1超时未支付
                    ordersService.closeTimeOutJob(order.getOrderId());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
